package com.senran.robot.controller;

import com.senran.robot.service.AutomaticReplyService;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import java.io.File;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/hello")
public class HelloWorldController {

    @Autowired
    private AutomaticReplyService automaticReplyService;

    @RequestMapping("/say")
    public String say(){
        return "Hello World";
    }

    @RequestMapping("/selenium")
    public String selenium(){
        return "selenium";
    }

    @RequestMapping("/chrome/{roomId}")
    public String chrome(@PathVariable Integer roomId) {
        automaticReplyService.getRoomSend(roomId);
        return "chrome";
    }

    @RequestMapping("/firefox")
    public String firefox() throws InterruptedException {
        System.setProperty("webdriver.gecko.driver", "/usr/local/bin/geckodriver");
        FirefoxOptions firefoxOptions = new FirefoxOptions();
        firefoxOptions.addArguments("--headless");
        firefoxOptions.addArguments("--no-sandbox");
        WebDriver webDriver = new FirefoxDriver();
        webDriver.manage().window().maximize();
        webDriver.get("http://www.baidu.com");

        Thread.sleep(3000);

        File src = ((TakesScreenshot)webDriver).getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(src, new File("gScreenshot.png"));
        }catch (Exception ex){
            ex.printStackTrace();
        }

        System.out.println(webDriver.getTitle());
        return "firefox";
    }

    @RequestMapping("/phantomjs")
    public String phantomjs() throws InterruptedException {
        System.setProperty("phantomjs.binary.path", "/usr/local/bin/phantomjs");
        WebDriver webDriver = new PhantomJSDriver();
        webDriver.manage().window().maximize();
        webDriver.get("http://www.baidu.com");

        Thread.sleep(3000);

        File src = ((TakesScreenshot)webDriver).getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(src, new File("pScreenshot.png"));
        }catch (Exception ex){
            ex.printStackTrace();
        }

        System.out.println(webDriver.getTitle());
        return "phantomjs";
    }
}
